from flask import Blueprint, request, jsonify
from utils.utils import build_fail_response, confirm_params_type
import os
import time
from public_listen_db import SQLServerDatabase, connection_string
from tqdm import tqdm

# 创建蓝图
select_public_binfile_save_page = Blueprint('select_public_binfile_save_page', __name__)
def get_bin_files(folder_path):
    bin_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".bin"):
                bin_files.append(os.path.join(root, file))
    return bin_files

def save_to_database(bin_files):
    # 创建数据库连接对象
    with SQLServerDatabase(connection_string) as db:
        # 记录开始时间
        # start_time = time.time()
        # total_rows = len(bin_files)  # 记录总条数

        # 开始事务
        with db.conn:
            with db.conn.cursor() as cursor:
                # 使用tqdm库实时显示进度
                for bin_file in tqdm(bin_files, desc="插入数据库中", unit="文件"):
                    # 格式化路径为 Windows 风格的路径
                    bin_file = bin_file.replace('/', '\\')
                    file_name_with_ext = os.path.basename(bin_file)
                    file_name, _ = os.path.splitext(file_name_with_ext)
                    # 处理华为 HW-0-EA132500050773.bin 的问题
                    file_name = file_name.split("-")[-1] if 'HW' in file_name.upper() else file_name
                    cursor.execute("INSERT INTO test (binpath, binname) VALUES (?,?)", (bin_file, file_name))

        # 记录结束时间
        end_time = time.time()
        # elapsed_time = end_time - start_time  # 计算总耗时

        # print(f"spent time: {elapsed_time:.2f}s")
        # print(f"total: {total_rows}")


@select_public_binfile_save_page.route('/pyapi/process_folder_data', methods=['POST'])
def process_folder():
    try:
        data = request.json
        folder_path = data.get('folder_path')

        if not folder_path:
            return jsonify({"message": "No folder path provided"}), 400

        if not os.path.exists(folder_path):
            return jsonify({"message": "该文件夹不存在"}), 400

        bin_files = get_bin_files(folder_path)
        save_to_database(bin_files)

        return jsonify({"message": "执行成功", "total_files": len(bin_files)})
    except Exception as e:
        return build_fail_response(message=str(e), params=confirm_params_type(request))
